<?php
/**
 * This is a simple POS front end. This demo uses a mix of PHP and Javascript.
 * A Javascript only version should be possible as well...
 * @copyright 2008 Nicolas Schudel
 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
 */


class OrderCreator {
	public $product_ids; // array of product IDs
	public $success; // if the order passed or not
	private $price;
	
	private $products; // array of ProductDTOs
	private $orderDTO;
	
	function __construct($product_ids_raw, $price) {
		require_once('../services/dto/OrderDTO.php');
		require_once('../services/dto/ProductDTO.php');
		require_once('../services/POSServices.php');
		
		$this->product_ids = array();
		$this->price = $price;
		$this->products = array();
		
		if (!is_array($product_ids_raw)) {
			if (sizeof($product_ids_raw) == 1) array_push($this->product_ids, $product_ids_raw);
			else $this->product_ids = explode("+", $product_ids_raw);
		} else {
			$this->product_ids = $product_ids_raw;
		}
	}
	
	public function execute() {
		$this->createProductDTOs();
		$this->createOrderDTO();
		$this->submitToService();
		return $this->orderDTO;
	}
	
	private function createProductDTOs() {
		foreach ($this->product_ids as &$value) {
			$productDTO = new ProductDTO;
			$productDTO->pid = $value;
			array_push($this->products, $productDTO);
		}
	}
	
	private function createOrderDTO() {
		$dto = new OrderDTO();
		$dto->products = $this->products;
		$dto->price = $this->price;
		$dto->currency = "CHF";
		$dto->method = "cod";
		$dto->cashier = "";
		$this->orderDTO = $dto;
	}
	
	private function submitToService() {
		$service = new POSServices;
		$this->success = $service->makeOrder($this->orderDTO);
	}
}

$action = (isset($_GET['action']) ? $_GET['action'] : '');
if ($action == "save") {
	$pids = $_POST['product_ids'];
	$price = $_POST['price'];
	
	$orderCreator = new OrderCreator($pids, $price);
	$order = $orderCreator->execute();
	if ($orderCreator->success) {
		echo "The Order has submitted the products ". implode(",", $orderCreator->product_ids) . " for a total price of " . $order->price;
	}
}
?>

<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
<html dir="ltr" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>POS Demo using AJAX and PHP</title>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">

var orderTotal = 0;
var userTotal = null;
var previousPrice = null;
var pids = new Array();
var currency = "CHF";

function init() {
	$('product_ids').activate();
	
	new Form.Element.Observer('product_ids', 2, productInputHandler);
	new Form.Element.Observer('price', 0.5, priceInputHandler);
}

function productInputHandler(el, value) {
	if (value != "") {
		pids = value.split('+');
		
		// First get rid of the previous contents
		$('products').innerHTML = "";
		orderTotal = 0;
		
		// Now refill the table with the new Product IDs
		pids.each(function(num) {getProduct(num)});
	}
}

function priceInputHandler(el, value) {
	if (value != "") {
		userTotal = value;
		$('order_total').innerHTML = Math.round(userTotal*100)/100;
	} else if (orderTotal > 0) {
		$('order_total').innerHTML = Math.round(orderTotal*100)/100;
	}
}

function getProduct(pid) {
	pid = parseInt(pid);
	if (pid > 0) new Ajax.Request("../json.php?POSServices.getProduct/" + pid, {method: "get", onSuccess: parseAjaxResponse});
}

function parseAjaxResponse(transport) {
	var jsonObj = eval("("+transport.responseText+")");
	if (jsonObj.name != null || jsonObj.price != 0 && jsonObj.price != null) {
		$('products').innerHTML += '<tr class="dataTableRow"><td>' + jsonObj.name + '<\/td><td>' + jsonObj.price + '<\/td><\/tr>';
		orderTotal += jsonObj.price;
		var roundedTotal = Math.round(orderTotal * 100) / 100;
		$('product_total').innerHTML = roundedTotal;
		if ($('price').value == previousPrice || previousPrice == null) {
	  		$('price').value = roundedTotal;
			previousPrice = roundedTotal;
		}
	}
}

function checkForm() {
	if (pids.length <1) {
   	alert("Please enter at least one product.");
		return false;
   }
	if (pids.indexOf(0) != -1) {
   	alert("One of the product IDs is not valid.");
		return false;
   }
	if ($('order_total').innerHTML == 0 || $('order_total').innerHTML == "") {
		alert("Please enter a price.");
		return false;
	}
	var answer = confirm("Are you sure you would like to buy the products " + pids.join(",") + " for " + $('order_total').innerHTML + "?")
	if (answer) {
		return true
	} else {
		return false;
	}
}

</script>

<style type="text/css">
body {
	min-width:755px;
	padding:1em;
}
.clear {
	clear:both;
}
.preview {
	border:2px solid #cdcdcd;
	width:100%;
	height:200px;
	overflow:scroll;
	border-collapse:collapse;
	border-spacing:0;
	margin-bottom:20px;
}
.preview th, .preview td {
	text-align:left;
	padding: 0.4em;
}
.preview th {
	height:1em;
}
label{
	width:20%;
	float: left;
	padding:0.2em 0 0 0;
}
.inputarea {
	width:40%;
	display:block;
	float:left;
	margin-bottom:10px;
	overflow:hidden;
}
.notice {
	width:40%;
	display:block;
	float:left;
	padding:0.2em 0 0 0;
	color:#8d2525;
}
	
</style>
</head>
<body onload="init()">
	<h1>Create Order</h1>
	<table class="preview" summary="A preview of the Products">
		<thead class="dataTableHeadingRow">
			<tr>
				<th width="75%">Product Name</th>
				<th width="25%">Product Price</th>
			</tr>
		</thead>
		<tbody id="products">
			<tr class="dataTableRow"><td>&nbsp;</td><td>&nbsp;</td></tr>
		</tbody>
		<tfoot>
			<tr>
				<td></td>
				<td>Products Total: <span class="currency">&nbsp;</span><span id="product_total">0</span></td>
			</tr>
			<tr>
				<td></td>
				<td>Order Total: <span class="currency">&nbsp;</span><span id="order_total">0</span></td>
			</tr>
		</tfoot>
	</table>
	
	<form name="create_order" action="<?php echo($_SERVER['PHP_SELF']); ?>?page=&amp;action=save" method="post" onsubmit="return checkForm(this);">
		<label for="product_ids">Product IDs: </label>
		<span class="inputarea"><input type="text" name="product_ids" id="product_ids" size="40"></span>
		<span class="notice">*separated by plus-sign (eg. 10+12+678)</span>
		<br class="clear" />
		<label for="price">Order Total: </label>
		<span class="inputarea"><input type="text" name="price" id="price" size="20"></span>
		<span class="notice">*price of entire order including rebates and taxes</span>
		<br class="clear" />
		<label>&nbsp;</label>
		<input type="submit" alt="Save" value="Save">
	</form>
	
</body>
</html>